using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Blog.IService;
using Blog.Command;
using Blog.Command.Utility;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.IdentityModel.Tokens.Jwt;

namespace Blog.Jwt.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthoizeController :ControllerBase
    {
        private readonly IWriterInfoService _iWriterInfoService;

        public AuthoizeController(IWriterInfoService iWriterInfoService)
        {
            _iWriterInfoService = iWriterInfoService;
        }

        [HttpGet]
        public async Task<ApiResult> Login(string userName, string userPwd)
        {
            string pwd = MD5Helper.MD5Encrypt32(userPwd);
            var writer = await _iWriterInfoService.FindAsync(c => c.UserName == userName && c.UserPwd == pwd);
            if (writer != null)
            {
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, writer.Name),
                    new Claim("Id", writer.Id.ToString()),
                    new Claim("UserName", writer.UserName)
                };
                var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("aAdfe11Fwfarasff4d5A2"));

                var token = new JwtSecurityToken(
                    issuer: "http://localhost:5183",
                    audience: "http://localhost:5159",
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return ApiResultHelper.Success(jwtToken);
            }
            else
            {
                return ApiResultHelper.Error("账号或密码错误");
            }
        }
    }
}